package com.chaofan.messagebook.config;

import com.chaofan.messagebook.mapper.BookMapper;
import com.chaofan.messagebook.mapper.MessageMapper;
import jakarta.enterprise.context.RequestScoped;
import jakarta.enterprise.context.SessionScoped;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;
import java.io.Serial;
import java.io.Serializable;

/**
 * @author 李超凡
 * @since 2022/4/2 23:39
 */
@RequestScoped
public class MyBatis implements Serializable {

    @Serial
    private static final long serialVersionUID = 4642030686894595022L;

    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            DataSource dataSource = DataSourceFactory.getDataSource();
            TransactionFactory transactionFactory = new JdbcTransactionFactory();
            Environment environment = new Environment("development", transactionFactory, dataSource);
            Configuration configuration = new Configuration(environment);
            configuration.addMapper(BookMapper.class);
            configuration.addMapper(MessageMapper.class);
            configuration.setMapUnderscoreToCamelCase(true);
            configuration.setCacheEnabled(true);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public SqlSession getSession() {
        return sqlSessionFactory.openSession();
    }
}
